package lock;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class AccessLimitControl {
    final Semaphore semaphore = new Semaphore(3);
    public String access() throws InterruptedException {
        // 如果超过许可证数量，其它线程在此等待
        semaphore.acquire();
        try {
            // TODO: todo
            Thread.sleep(100);
            return UUID.randomUUID().toString();
        }finally {
            semaphore.release();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        List<String> results = new ArrayList<>();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                3,
                6,
                10,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10)
        );

        AccessLimitControl limitControl = new AccessLimitControl();
        try {
            for (int i = 0; i < 15; i++) {
                executor.submit(()->{
                    try {
                        results.add(limitControl.access());
                        System.out.println("limitControl.access() = " + limitControl.access());
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
                });
            }
            executor.awaitTermination(5,TimeUnit.SECONDS);
            System.out.println("results.size() = " + results.size());
            System.out.println("Unique UUIDs generated: " + results.stream().distinct().count());
        }
        finally {
            executor.shutdown();
        }
    }
}
